import React, { useState } from 'react'
import NavBar from '@/components/nav-bar'
import Input from '@/components/input'
import styles from './index.module.scss'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { setCode, login } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router'
export default function Login() {
  const history = useHistory()
  const location = useLocation()
  const formik = useFormik({
    initialValues: {
      mobile: '13095567654',
      code: '246810',
    },

    // 发送登录请求
    onSubmit: async (values) => {
      await dispatch(login(values))
      Toast.success('登录成功', 2)
      // console.log(location.state)
      // console.log(location)
      if (location.state) {
        history.replace(location.state.from)
      } else {
        history.replace('/home')
      }
    },
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('不能为空')
        .max(11, '手机号位数输入有误')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .max(6, '验证码个数输入有误')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  })
  // console.log(formik)
  const {
    values,
    handleChange,
    handleSubmit,
    handleBlur,
    errors,
    touched,
    isValid,
  } = formik
  const dispatch = useDispatch()
  const [timer, setTimer] = useState(0)
  // 获取验证码
  const onExtrackClick = async () => {
    if (timer > 0) return
    if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }
    // 发送获取验证码
    await dispatch(setCode(values.mobile))
    Toast.success('获取成功', 2)
    setTimer(60)
    let timerValue = setInterval(() => {
      setTimer((timer) => {
        if (timer === 1) {
          clearInterval(timerValue)
        }
        return timer - 1
      })
    }, 1000)
  }
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <Input
              name="mobile"
              onBlur={handleBlur}
              autoComplete="off"
              value={values.mobile}
              onChange={handleChange}
              placeholder="请输入手机号"
            ></Input>
            {touched.mobile && errors.mobile ? (
              <div className="validate">{errors.mobile}</div>
            ) : null}
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <Input
              name="code"
              onBlur={handleBlur}
              autoComplete="off"
              value={values.code}
              placeholder="请输入验证码"
              extra={timer === 0 ? '获取验证码' : timer + 's后重新获取'}
              onChange={handleChange}
              onExtrackClick={onExtrackClick}
            ></Input>
            {touched.code && errors.code ? (
              <div className="validate">{errors.code}</div>
            ) : null}
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            className={classNames('login-btn', { disabled: !isValid })}
            disabled={!isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
